import { ReactElement, useState, useEffect } from 'react'
import { Space, Button, message, Empty, Radio, Modal } from 'antd'
import style from './index.module.less'
import classNames from 'classnames'
import { awaitWrap, filterEmptyStr } from '@src/assets/js/tool'
import { getCaseDetailRequest, getScoreRequest } from './ajax'
import { CaseSchema } from '@src/components/schema/caseSchema'
import { ScoreSchema, ScoreTotalSchema } from '@src/components/schema/scoreSchema'
import { ExclamationCircleOutlined } from '@ant-design/icons'
import { json2Excel } from '@js/excel'
import Score from './components/score'
import Serieno from '@src/pages/admin/components/serieno'
import { useDispatch } from 'react-redux'

const { confirm } = Modal

// 初始化案件数据
async function initData (caseid: string, setCaseDetail: (v: CaseSchema) => void): Promise<void> {
  const hide = message.loading('加载中', 120)
  const [e, d] = await awaitWrap(getCaseDetailRequest(caseid))
  hide()
  if (e === null && d !== null) {
    setCaseDetail(d)
  }
}

async function initScore (caseid: string, setScore: (v: ScoreTotalSchema | null) => void, setLoading: (v: boolean) => void, setList: (v: ScoreSchema[]) => void): Promise<void> {
  setLoading(true)
  const [e, d] = await awaitWrap(getScoreRequest(caseid))
  setLoading(false)
  if (e === null && d !== null) {
    setScore(d)
    setList(d.score_list)
  }
}

// 下载excel二次确认
function confirmDownload (caseDetail: CaseSchema | null, list: ScoreSchema[], score: ScoreTotalSchema): void {
  if (caseDetail === null) {
    message.warning('案件数据不存在').then(null, null)
    return undefined
  }
  confirm({
    icon: <ExclamationCircleOutlined />,
    content: '您确定要导出excel吗？',
    onOk () {
      downloadExcel(caseDetail, list, score)
    }
  })
}

function downloadExcel (caseDetail: CaseSchema, list: ScoreSchema[], score: ScoreTotalSchema): void {
  const { accepter, processer, accepter_serieno: as, processer_serieno: ps } = caseDetail
  json2Excel([
    { data: getExcelLines(list.filter(li => li.scope === 'accepter'), fixedNum(score.accepter_score)), sheetname: `受理秘书-${accepter}-${as}-绩效` },
    { data: getExcelLines(list.filter(li => li.scope === 'processer'), fixedNum(score.processer_score)), sheetname: `办案秘书-${processer}-${ps}-绩效` }
  ], `${caseDetail.caseno_desc}-考核计算表`)
}

function getExcelLines (list: ScoreSchema[], total: string): Array<{ [k: string]: any }> {
  const arr = list.map(li => {
    let describe = ''
    if (li.desc_list instanceof Array) {
      describe = li.desc_list.map((li, i) => `${i + 1}、${li.title}：${li.value}`).join('；')
    } else if (typeof li.count === 'number') {
      const u: string = typeof li.unit === 'string' ? li.unit : ''
      describe = `${li.count}${u}`
    }
    return {
      序号: li.orderno,
      类型: li.title,
      描述: describe,
      分数小结: li.description,
      得分: fixedNum(li.score, 2)
    }
  })
  arr.push({
    序号: '总分',
    类型: '',
    描述: '',
    分数小结: '',
    得分: total
  })
  return arr
}

function fixedNum (v: number, unit: number = 3): string {
  if (v === 0 || v === undefined || v === null) {
    return '0'
  }
  if (typeof v === 'number') {
    return v.toFixed(unit)
  }
  return v
}

interface Props {
  meta: {
    id: string
  }
}

function Main ({ meta }: Props): ReactElement {
  const dispatch = useDispatch()
  const [caseDetail, setCaseDetail] = useState<CaseSchema | null>(null)
  const [list, setList] = useState<ScoreSchema[]>([])
  const [currentList, setCurrentList] = useState<ScoreSchema[]>([])
  const [listType, setListType] = useState('受理秘书绩效')
  const [subtract, setSubtract] = useState(0)
  const [add, setAdd] = useState(0)
  const [total, setTotal] = useState(0)
  const [score, setScore] = useState<ScoreTotalSchema | null>(null)
  const [scoreLoading, setScoreLoading] = useState(false)
  useEffect(() => {
    if (typeof meta.id === 'string') {
      initData(meta.id, setCaseDetail).catch(e => console.error(e))
      initScore(meta.id, setScore, setScoreLoading, setList).catch(e => console.error(e))
    }
  }, [meta])
  useEffect(() => {
    let s = 0
    let a = 0
    const l = list.filter(li => {
      if (listType === '受理秘书绩效') {
        return li.scope === 'accepter'
      } else if (listType === '办案秘书绩效') {
        return li.scope === 'processer'
      }
      return true
    })
    l.forEach(li => {
      if (li.score > 0) {
        a += li.score
      } else if (li.score < 0) {
        s += li.score
      }
    })
    setSubtract(s)
    setAdd(a)
    setTotal(s + a)
    setCurrentList(l)
  }, [list, listType])
  return (
    <div className={style.container}>
      <div className={style['container-header']}>
        <div className={style['case-info-line']}>
            <span className={style['case-info-line-cell']}>
              <span>案号：{filterEmptyStr(caseDetail !== null ? caseDetail.caseno_desc : '')}</span>
              <span className={style.series}><Serieno data={caseDetail} /></span>
            </span>
            <span className={style['case-info-line-cell']}>受理秘书：{filterEmptyStr(caseDetail !== null ? caseDetail.accepter : '')}</span>
            <span className={style['case-info-line-cell']}>办案秘书：{filterEmptyStr(caseDetail !== null ? caseDetail.processer : '')}</span>
          </div>
          <div className={style['score-line']}>
            <Score caseDetail={caseDetail} score={score} loading={scoreLoading}/>
            <div className={style['btn-block']}>
              <Space>
                <Button type='primary' ghost onClick={() => confirmDownload(caseDetail, list, score as ScoreTotalSchema)}>导出excel</Button>
              </Space>
            </div>
          </div>
      </div>
      <div className={style.body}>
        <div className={style.inner}>
          <div className={style.header}>
            <span className={style['header-title']}>绩效详情</span>
            <Radio.Group value={listType} onChange={e => setListType(e.target.value)}>
              <Radio.Button value='受理秘书绩效'>受理秘书绩效</Radio.Button>
              <Radio.Button value='办案秘书绩效'>办案秘书绩效</Radio.Button>
            </Radio.Group>
          </div>
          <table className={style.table}>
            <thead>
              <tr>
                <th style={{ width: '80px' }}>序号</th>
                <th>类型</th>
                <th colSpan={4}>描述</th>
                <th colSpan={2}>分数小结</th>
                <th>得分</th>
              </tr>
            </thead>
            <tbody>
              {
                currentList.length > 0 && (
                  currentList.map((li, i: number) => {
                    const u: string = typeof li.unit === 'string' ? li.unit : ''
                    return (
                          <tr key={i}>
                            <td style={{ width: '80px' }}>{i + 1}</td>
                            <td colSpan={1}>{li.title}</td>
                            <td colSpan={4}>
                              {li.desc_list instanceof Array
                                ? (
                                    li.desc_list.map((li, i: number) => {
                                      return <span className={style.desc} key={i}>{li.title}：{li.value}</span>
                                    })
                                  )
                                : (
                                    typeof li.count === 'number' && `${li.count}${u}`
                                  )}
                            </td>
                            <td colSpan={2}>{li.description}</td>
                            <td>{typeof li.score === 'number' ? li.score.toFixed(2) : 0}</td>
                          </tr>
                    )
                  })
                )
              }
            </tbody>
          </table>
          {list.length === 0 && <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />}
        </div>
      </div>
      <div className={style.footer}>
        <span className={style['footer-page']}>
          <span>全部</span>
          <span className={style['footer-page-num']}>{currentList.length}</span>
          <span>项</span>
        </span>
        <div className={style['footer-operates']}>
          <Space size={24}>
            <span className={style['score-btn']}>合计加分<span className={style['score-btn-num']}>+{add.toFixed(2)}</span></span>
            <span className={style['score-btn']}>合计减分<span className={style['score-btn-num']}>{subtract.toFixed(2)}</span></span>
            <span className={classNames(style['score-btn'], style.active)}>合计总分<span className={style['score-btn-num']}>{total.toFixed(2)}</span></span>
          </Space>
        </div>
      </div>
    </div>
  )
}

export default Main
